Event.observe ( window, 'load', bootstrap );

function bootstrap () {
  TableKit.options.editAjaxURI = '/rest/datasheet';
  
  table_kit_select_input_as_boolean ( $w( 'authorization_owner authorization_writer authorization_follower' ) );
  
  $( 'datasheet_id'      ).on ( 'change',  datasheet_changed         ); /* mouseup */
  $( 'user'              ).on ( 'change',  user_changed              );
  
  $( 'neo_datasheet_id'  ).on ( 'change',  neo_datasheet_id_changed  ); /* keyup */
  $( 'neo_repository_id' ).on ( 'change',  neo_repository_id_changed );
  
  var re = '^(';
  $$( 'select#datasheet_id option' ).each ( function ( node ) { re = re + node.label + '|' } );
  re = re + '-)$';
  names_re = new RegExp ( re );
  
  reset_users_table ();
}

function neo_datasheet_id_changed () {
  var datasheet = $( 'neo_datasheet_id' ).value;
  
  var name_re = new RegExp ( '^[A-Z][A-Z0-9]+_[0-9]{4,5}$' );
  
  if ( name_re.test ( datasheet ) && ! names_re.test ( datasheet ) ) {
    enable  ( 'neo_repository_id' );
  }
  else {
    disable ( 'neo_repository_id' );
  }
}

function neo_repository_id_changed () {
  if ( $( 'neo_repository_id' ).value != '' ) {
    enable  ( 'create' );
  }
  else {
    disable ( 'create' );
  }
}

function user_changed () {
  var user      = $( 'user'         ).value;
  var datasheet = $( 'datasheet_id' ).value;
  
  if ( user != '' && datasheet != '' ) {
    new Ajax.Request ( '/rest/user/' + user + '/datasheet/' + datasheet + '?authorization=writer', {
      method         : 'put',
      requestHeaders : { Accept : 'application/json' },
      onComplete     : function () {
        datasheet_changed ();
        
        $( 'user' ).setValue ( '' );
      }
    } );
  }
}

function datasheet_changed () {
  var datasheet = $( 'datasheet_id' ).value;
  
  if ( datasheet != '' ) {
    new Ajax.Request ( '/rest/datasheet/' + datasheet, {
      method         : 'get',
      requestHeaders : { Accept : 'application/json' },
      onComplete     : function ( response ) {
        $( 'users_table' ).replace ( users_authorizations_table ( response.responseJSON, 'datasheet', datasheet ) );
        
        TableKit.Sortable.init ( 'users_table' );
        TableKit.reload ();
        
        enable ( 'user' );
        $( 'user' ).style.display = '';
        
        $( 'datasheet_repository_id' ).replace ( "<td id=\"datasheet_repository_id\" title=\"" + response.responseJSON.repository_url + "\">" + response.responseJSON.repository_id + "</td>" );
        disable ( 'datasheet_id_filter' );
      },
      onFailure      : function ( response ) {
        reset_users_table ();
      }
    } );
  }
  else {
    reset_users_table ();
  }
}

function reset_users_table () {
  $( 'users_table' ).replace ( '<div id="users_table"></div>' );
  
  disable ( 'user' );
  $( 'user' ).style.display = 'none';
  
  $( 'datasheet_repository_id' ).replace ( "<td id=\"datasheet_repository_id\"></td>" );
  enable ( 'datasheet_id_filter' );
}
